package org.apimgr.service;

import com.alibaba.fastjson.JSON;
import org.apimgr.dto.ApiUserReqDto;
import org.apimgr.dto.ApiUserResDto;
import org.apimgr.entity.ApiUser;
import org.apimgr.enums.PTExceptionCode;
import org.apimgr.exception.PTUnCheckedException;
import org.apimgr.mapper.ApiUserMapper;
import org.apimgr.util.CommonsUtil;
import org.apimgr.util.JedisUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by yangjie on 2017/8/1.
 * 用户Service
 */
@Service
public class ApiUserService {

    @Resource
    private ApiUserMapper apiUserMapper;


    @Resource
    private JedisUtil jedisUtil;
    /**
     * 获取登录用户
     * @param apiUserReqDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public ApiUserResDto getLoginUser(ApiUserReqDto apiUserReqDto){
        checkLoginParam(apiUserReqDto);
        ApiUserResDto resDto = new ApiUserResDto();
        ApiUser loginUser = apiUserMapper.getLoginUser(apiUserReqDto);
        if(loginUser == null) throw  new PTUnCheckedException(PTExceptionCode.SYSUSER_LOGIN_FAIL.getCode());

        String token = CommonsUtil.createUUID();
        String tk = jedisUtil.get(loginUser.getId()+"");
        if(tk != null){
            jedisUtil.del(tk);
        }
        jedisUtil.set(loginUser.getId()+"",token);

        jedisUtil.set(token, JSON.toJSONString(loginUser));
        jedisUtil.expilre(token,30);
        resDto.setApiUser(loginUser);
        resDto.setToken(token);
        return  resDto;
    }


    /**
     * 检查登录时的对象参数
     * @param reqDto
     */
    public void checkLoginParam(ApiUserReqDto reqDto){
        if(CommonsUtil.isStringEmpty(reqDto.getUsername())){
            throw  new PTUnCheckedException(PTExceptionCode.SYSUSER_USERNAME_NULL.getCode());
        }
        if(CommonsUtil.isStringEmpty(reqDto.getPassword())){
            throw  new PTUnCheckedException(PTExceptionCode.SYSUSER_PASSWORD_NULL.getCode());
        }
    }


}
